#!/usr/bin/env bash
set -eo pipefail

BUILDPACK_INSTALL_PATH="/tmp/buildpacks"

download_buildpack() {
    buildpack_url="$1"
    buildpack_name=$(basename $buildpack_url)
    buildpack_commit="$2"

    echo "Fetching $buildpack_name..."

    set +e
    git clone --branch $buildpack_commit --depth 1 $buildpack_url $BUILDPACK_INSTALL_PATH/$buildpack_name &>/dev/null
    SHALLOW_CLONED=$?
    set -e
    if [ $SHALLOW_CLONED -ne 0 ]; then
        # if the shallow clone failed partway through, clean up and try a full clone
        rm -rf $BUILDPACK_INSTALL_PATH/$buildpack_name
        git clone --quiet $buildpack_url $BUILDPACK_INSTALL_PATH/$buildpack_name
        pushd $BUILDPACK_INSTALL_PATH/$buildpack_name &>/dev/null
            git checkout --quiet $buildpack_commit
        popd &>/dev/null
    else
        # clean .git directory
        rm -rf $BUILDPACK_INSTALL_PATH/$buildpack_name/.git 
    fi

    echo "Done."
}


mkdir -p $BUILDPACK_INSTALL_PATH

#download_buildpack https://github.com/goodrain/heroku-buildpack-nodejs.git             rainbond
#download_buildpack https://github.com/goodrain/heroku-buildpack-python.git             rainbond
#download_buildpack https://github.com/goodrain/heroku-buildpack-php.git                rainbond
#download_buildpack https://github.com/goodrain/heroku-buildpack-go.git                 rainbond
#download_buildpack https://github.com/goodrain/heroku-buildpack-static.git             rainbond
#download_buildpack https://github.com/goodrain/heroku-buildpack-static-backports.git   master
#download_buildpack https://github.com/goodrain/heroku-buildpack-java.git               master
#download_buildpack https://github.com/goodrain/heroku-buildpack-gradle.git             master
# 修改权限
chown rain.rain /tmp/buildpacks -R
